package homework;

// key-value 模型
public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public int put(int key, int value) {
        // write code here
        Node node = new Node(key, value);
        int index = key % this.array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key == key){
                cur.value = value;
            }else{
                cur = cur.next;
            }
        }
        //cur == null 这里写一个头插法
        node.next = array[index];
        array[index] = node;
        this.size++;
        //判断负载因子
        if(loadFactor() >= LOAD_FACTOR){
            resize();
        }

        return -1;
    }


    private void resize() {
        // write code here
        Node[] tmpArr = new Node[this.array.length * 2];
        //遍历所有元素，重新哈希
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            while(cur != null){
                int newIndex = cur.key % tmpArr.length;
                Node curNext = cur.next;
                //这里要写一个头插法
                cur.next = tmpArr[newIndex];
                tmpArr[newIndex] = cur;
                cur = curNext;
            }
        }
        this.array = tmpArr;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        // write code here
        this.array = new Node[DEFAULT_SIZE];
    }


    public int get(int key) {
        // write code here
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null){
            if(cur.key != key){
                cur = cur.next;
            }else{
                return cur.value;
            }
        }
        return -1;
    }
}
